package com.learn.eduuserboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.eduuserboot.entity.User;
import com.learn.eduuserboot.mapper.UserMapper;
import com.learn.eduuserboot.service.UserService;
import com.learn.eduuserboot.utils.Md5Utils;
import com.learn.eduuserboot.utils.RandomCharecters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author m
 * @since 2022-04-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    static String  salt = RandomCharecters.getRandomString(4);

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer checkPhone(String phone) {
        QueryWrapper<User> qw = new QueryWrapper();
        qw.eq("phone", phone);
        return userMapper.selectCount(qw);
    }

    public String md5Password(String password,String salt){
        password=salt+password;
        password= Md5Utils.getMD5String(password);
        return password;
    }

    @Override
    public void register(String phone, String password, String nickname, String headimg) {
         password = md5Password(password,salt);
        User user = new User();
        user.setPhone(phone).setPassword(password).setName(nickname).setPortrait(headimg).setSalt(salt);
        userMapper.insert(user);
    }

    @Override
    public User login(String phone, String password) {
        QueryWrapper<User> wq = new QueryWrapper<>();
        wq.eq("phone", phone);
        User user = userMapper.selectOne(wq);
        String salt = user.getSalt();
        String md5 = md5Password(password, salt);
        if (md5.equals(user.getPassword())){
            return userMapper.selectOne(wq);
        }else {
            return null;
        }
    }
}
